package com.fary.web.servlet.mvc.method.annotation;

import com.fary.core.MethodParameter;
import com.fary.core.ResolvableType;
import com.fary.util.*;
import com.fary.web.bind.annotation.MatrixVariable;
import com.fary.web.bind.annotation.ValueConstants;
import com.fary.web.bind.support.WebDataBinderFactory;
import com.fary.web.context.request.NativeWebRequest;
import com.fary.web.context.request.RequestAttributes;
import com.fary.web.method.support.HandlerMethodArgumentResolver;
import com.fary.web.method.support.ModelAndViewContainer;
import com.fary.web.servlet.HandlerMapping;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class MatrixVariableMapMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        MatrixVariable matrixVariable = parameter.getParameterAnnotation(MatrixVariable.class);
        return (matrixVariable != null && Map.class.isAssignableFrom(parameter.getParameterType()) &&
                !StringUtils.hasText(matrixVariable.name()));
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception {

        @SuppressWarnings("unchecked")
        Map<String, MultiValueMap<String, String>> matrixVariables =
                (Map<String, MultiValueMap<String, String>>) request.getAttribute(
                        HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

        if (CollectionUtils.isEmpty(matrixVariables)) {
            return Collections.emptyMap();
        }

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        MatrixVariable ann = parameter.getParameterAnnotation(MatrixVariable.class);
        Assert.state(ann != null, "No MatrixVariable annotation");
        String pathVariable = ann.pathVar();

        if (!pathVariable.equals(ValueConstants.DEFAULT_NONE)) {
            MultiValueMap<String, String> mapForPathVariable = matrixVariables.get(pathVariable);
            if (mapForPathVariable == null) {
                return Collections.emptyMap();
            }
            map.putAll(mapForPathVariable);
        } else {
            for (MultiValueMap<String, String> vars : matrixVariables.values()) {
                vars.forEach((name, values) -> {
                    for (String value : values) {
                        map.add(name, value);
                    }
                });
            }
        }

        return (isSingleValueMap(parameter) ? map.toSingleValueMap() : map);
    }

    private boolean isSingleValueMap(MethodParameter parameter) {
        if (!MultiValueMap.class.isAssignableFrom(parameter.getParameterType())) {
            ResolvableType[] genericTypes = ResolvableType.forMethodParameter(parameter).getGenerics();
            if (genericTypes.length == 2) {
                return !List.class.isAssignableFrom(genericTypes[1].toClass());
            }
        }
        return false;
    }

}